﻿using System.Collections.Generic;
using System.IO;
using Cysharp.Threading.Tasks;
using Neatly.Load.Manager;
using UnityEngine;

namespace Neatly.Module
{
    public class I18nModule : ModuleSingleton<I18nModule>
    {
        private const string DEFAULT_LANGUAGE = "en";
        private string m_CurrentLanguage;

        private Dictionary<string, Dictionary<string, string>> m_AllLanguageMap;

        private static Dictionary<string, string> SystemLanguageMatchMap = new()
        {
            { "Chinese", "zh" },
            { "ChineseSimplified", "zh" },
            { "ChineseTraditional", "zh" },
            { "English", "en" },
        };

        public override async UniTask Init()
        {
            m_AllLanguageMap = new Dictionary<string, Dictionary<string, string>>();

            m_CurrentLanguage = PlayerPrefsHelper.GetLanguage(null);
            if (!string.IsNullOrEmpty(m_CurrentLanguage))
            {
                return;
            }

            string systemLanguage = Application.systemLanguage.ToString();
            m_CurrentLanguage = SystemLanguageMatchMap.GetValueOrDefault(systemLanguage, DEFAULT_LANGUAGE);
        }

        public void SetDefaultLanguage(string language)
        {
            m_CurrentLanguage = language;
        }

        public string GetValue(string key, string language = null)
        {
            if (string.IsNullOrEmpty(language))
            {
                language = m_CurrentLanguage;
            }

            m_AllLanguageMap.TryGetValue(language, out var map);
            if (map == null)
            {
                map = CreateLanguageMap(language);
                m_AllLanguageMap.Add(language, map);
            }

            if (!map.TryGetValue(key, out var text))
                text = '*' + key;
            return text;
        }

        private Dictionary<string, string> CreateLanguageMap(string language)
        {
#if UNITY_WEBGL
            if (language == "zh")
            {
                return new Dictionary<string, string>
                {
                    {"key", "临时数据"},
                };
            }
            return new Dictionary<string, string>
            {
                {"key", "临时数据"},
            };
#else
            var fileName = FileHashManager.Instance.GetFileName(NeatlyConfig.FOLDER_I18N, language);
            byte[] byteArray = FileModule.Instance.ReadFileBytes(Path.Combine(NeatlyConfig.FOLDER_I18N, fileName));
            var languageMap = new Dictionary<string, string>();
            string str = System.Text.Encoding.Default.GetString(byteArray);
            foreach (var lineInfo in str.Split('\n'))
            {
                var infoArray = lineInfo.Split(',');
                languageMap.Add(infoArray[0], System.Text.RegularExpressions.Regex.Unescape(infoArray[1]));
            }

            return languageMap;
#endif
        }
    }
}